/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intel.factorytest.activity;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.View;

public class PointerLocationView extends View {
    private static final String TAG = "Pointer";
    private static final int RECTLEN = 50;
    
    private Context ctx;
    
    // screen width
    private int widthScr = 0;
    // screen height
    private int heightScr = 0;
    
    private boolean isFirstDrawn = true;
    
    public static class PointerState {
        // Trace of previous points.
        private float[] intel_mat_mTraceX = new float[32];
        private float[] intel_mat_mTraceY = new float[32];
        private int intel_mat_mTraceCount;
        
        // True if the pointer is down.
        private boolean intel_mat_mCurDown;
        
        // Most recent coordinates.
        private MotionEvent.PointerCoords intel_mat_mCoords = new MotionEvent.PointerCoords();
        
        // Most recent velocity.
        private float intel_mat_mXVelocity;
        private float intel_mat_mYVelocity;
        
        public void clearTrace() {
            intel_mat_mTraceCount = 0;
        }
        
        public void addTrace(float x, float y) {
            int traceCapacity = intel_mat_mTraceX.length;
            if (intel_mat_mTraceCount == traceCapacity) {
                traceCapacity *= 2;
                float[] newTraceX = new float[traceCapacity];
                System.arraycopy(intel_mat_mTraceX, 0, newTraceX, 0, intel_mat_mTraceCount);
                intel_mat_mTraceX = newTraceX;
                
                float[] newTraceY = new float[traceCapacity];
                System.arraycopy(intel_mat_mTraceY, 0, newTraceY, 0, intel_mat_mTraceCount);
                intel_mat_mTraceY = newTraceY;
            }
            
            intel_mat_mTraceX[intel_mat_mTraceCount] = x;
            intel_mat_mTraceY[intel_mat_mTraceCount] = y;
            intel_mat_mTraceCount += 1;
        }
    }

    private final Paint intel_mat_mPaint;
    private final Paint intel_mat_mPathPaint;
    private boolean intel_mat_mCurDown;
    private int intel_mat_mActivePointerId;
    private final ArrayList<PointerState> intel_mat_mPointers = new ArrayList<PointerState>();
    
    
    private final FasterStringBuilderIntelMAT intel_mat_mText = new FasterStringBuilderIntelMAT();
    
    private boolean intel_mat_mPrintCoords = true;
    
    public PointerLocationView(Context ctx) {
        super(ctx);
        
        this.ctx = ctx;
        
        PointerLocation activity = (PointerLocation) this.ctx;
        widthScr = activity.widthScreen;
        heightScr = activity.heightScreen;
        
        setFocusable(true);
        
        intel_mat_mPaint = new Paint();
        intel_mat_mPaint.setAntiAlias(true);
        intel_mat_mPaint.setARGB(255, 255, 0, 0);
        intel_mat_mPaint.setStyle(Paint.Style.FILL);
        intel_mat_mPaint.setStrokeWidth(5);
        
        intel_mat_mPathPaint = new Paint();
        intel_mat_mPathPaint.setAntiAlias(false);
        intel_mat_mPathPaint.setARGB(255, 0, 255, 0);
        intel_mat_mPathPaint.setStyle(Paint.Style.FILL);
        intel_mat_mPathPaint.setStrokeWidth(1);
        
        PointerState ps = new PointerState();
        intel_mat_mPointers.add(ps);
        intel_mat_mActivePointerId = 0;
        
        logInputDeviceCapabilities();
    }
    
    private void logInputDeviceCapabilities() {
        int[] deviceIds = InputDevice.getDeviceIds();
        for (int i = 0; i < deviceIds.length; i++) {
            InputDevice device = InputDevice.getDevice(deviceIds[i]);
            if (device != null) {
                Log.i(TAG, device.toString());
            }
        }
    }

    public void setPrintCoords(boolean state) {
        intel_mat_mPrintCoords = state;
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {

        synchronized (intel_mat_mPointers) {
            initDrawn(canvas);
            final int NP = intel_mat_mPointers.size();
            // Pointer trace.
            for (int p = 0; p < NP; p++) {
                final PointerState ps = intel_mat_mPointers.get(p);

                // Draw path.
                final int N = ps.intel_mat_mTraceCount;
                float lastX = 0, lastY = 0;
                boolean haveLast = false;
                boolean drawn = false;
                for (int i = 0; i < N; i++) {
                    float x = ps.intel_mat_mTraceX[i];
                    float y = ps.intel_mat_mTraceY[i];
                    if (Float.isNaN(x)) {
                        haveLast = false;
                        continue;
                    }
                    if (haveLast) {
                        canvas.drawRect(whichRect(x, y), intel_mat_mPathPaint);
                        drawn = true;
                    }
                    lastX = x;
                    lastY = y;
                    haveLast = true;
                }
            }
        }

    }
    
    private void initDrawn(Canvas canvas) {
        int rectCountH = widthScr / RECTLEN;
        int rectCountV = heightScr / RECTLEN;
        
        for (int i = 0; i < rectCountH; i++) {
            canvas.drawRect(i * RECTLEN, 0, (i + 1) * RECTLEN, RECTLEN, intel_mat_mPaint);
            canvas.drawRect(i * RECTLEN, heightScr - RECTLEN, (i + 1) * RECTLEN, heightScr, intel_mat_mPaint);
        }
        
        for (int i = 0; i < rectCountV; i++) {
            canvas.drawRect(0, i * RECTLEN, RECTLEN, (i + 1) * RECTLEN, intel_mat_mPaint); 
            canvas.drawRect(widthScr - RECTLEN, i * RECTLEN, widthScr, (i + 1) * RECTLEN, intel_mat_mPaint);
        }
    }
    
    private Rect whichRect(float coordsX, float coordsY) {
        
        int NX = (int) coordsX / RECTLEN;
        int NY = (int) coordsY / RECTLEN;
        
        return new Rect(NX * RECTLEN, NY * RECTLEN, (NX + 1) * RECTLEN, (NY + 1) * RECTLEN);
    }
    
    private void logPointerCoords(MotionEvent.PointerCoords coords, int id) {
        Log.i(TAG, intel_mat_mText.clear()
                .append("Pointer ").append(id + 1)
                .append(": (").append(coords.x, 3).append(", ").append(coords.y, 3)
                .append(") Pressure=").append(coords.pressure, 3)
                .append(" Size=").append(coords.size, 3)
                .append(" TouchMajor=").append(coords.touchMajor, 3)
                .append(" TouchMinor=").append(coords.touchMinor, 3)
                .append(" ToolMajor=").append(coords.toolMajor, 3)
                .append(" ToolMinor=").append(coords.toolMinor, 3)
                .append(" Orientation=").append((float)(coords.orientation * 180 / Math.PI), 1)
                .append("deg").toString());
    }

    public void addTouchEvent(MotionEvent event) {
        synchronized (intel_mat_mPointers) {
            int action = event.getAction();
            
            int NP = intel_mat_mPointers.size();
            
            if (action == MotionEvent.ACTION_DOWN
                    || (action & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN) {
                final int index = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
                        >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; // will be 0 for down
                
                final int id = event.getPointerId(index);
                while (NP <= id) {
                    PointerState ps = new PointerState();
                    intel_mat_mPointers.add(ps);
                    NP++;
                }
                
                if (intel_mat_mActivePointerId < 0 ||
                        ! intel_mat_mPointers.get(intel_mat_mActivePointerId).intel_mat_mCurDown) {
                    intel_mat_mActivePointerId = id;
                }
                
                final PointerState ps = intel_mat_mPointers.get(id);
                ps.intel_mat_mCurDown = true;
                if (intel_mat_mPrintCoords) {
                    Log.i(TAG, intel_mat_mText.clear().append("Pointer ")
                            .append(id + 1).append(": DOWN").toString());
                }
            }
            
            final int NI = event.getPointerCount();
            
            intel_mat_mCurDown = action != MotionEvent.ACTION_UP
                    && action != MotionEvent.ACTION_CANCEL;

            
            for (int i=0; i<NI; i++) {
                final int id = event.getPointerId(i);
                final PointerState ps = intel_mat_mPointers.get(id);
                final int N = event.getHistorySize();
                for (int j=0; j<N; j++) {
                    event.getHistoricalPointerCoords(i, j, ps.intel_mat_mCoords);
                    if (intel_mat_mPrintCoords) {
                        logPointerCoords(ps.intel_mat_mCoords, id);
                    }
                    ps.addTrace(event.getHistoricalX(i, j), event.getHistoricalY(i, j));
                }
                event.getPointerCoords(i, ps.intel_mat_mCoords);
                if (intel_mat_mPrintCoords) {
                    logPointerCoords(ps.intel_mat_mCoords, id);
                }
                ps.addTrace(ps.intel_mat_mCoords.x, ps.intel_mat_mCoords.y);
            }
            
            if (action == MotionEvent.ACTION_UP
                    || action == MotionEvent.ACTION_CANCEL
                    || (action & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP) {
                final int index = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
                        >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; // will be 0 for UP
                
                final int id = event.getPointerId(index);
                final PointerState ps = intel_mat_mPointers.get(id);
                ps.intel_mat_mCurDown = false;
                if (intel_mat_mPrintCoords) {
                    Log.i(TAG, intel_mat_mText.clear().append("Pointer ")
                            .append(id + 1).append(": UP").toString());
                }
                
                if (action == MotionEvent.ACTION_UP
                        || action == MotionEvent.ACTION_CANCEL) {
                    intel_mat_mCurDown = false;
                } else {
                    if (intel_mat_mActivePointerId == id) {
                        intel_mat_mActivePointerId = event.getPointerId(index == 0 ? 1 : 0);
                    }
                    ps.addTrace(Float.NaN, Float.NaN);
                }
            }
            
            postInvalidate();
        }
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        addTouchEvent(event);
        return true;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        Log.i(TAG, "Trackball: " + event);
        return super.onTrackballEvent(event);
    }
    
    private static final class FasterStringBuilderIntelMAT {
        private char[] intel_mat_mChars;
        private int intel_mat_mLength;
        
        public FasterStringBuilderIntelMAT() {
            intel_mat_mChars = new char[64];
        }
        
        public FasterStringBuilderIntelMAT clear() {
            intel_mat_mLength = 0;
            return this;
        }
        
        public FasterStringBuilderIntelMAT append(String value) {
            final int valueLength = value.length();
            final int index = reserve(valueLength);
            value.getChars(0, valueLength, intel_mat_mChars, index);
            intel_mat_mLength += valueLength;
            return this;
        }
        
        public FasterStringBuilderIntelMAT append(int value) {
            return append(value, 0);
        }
        
        public FasterStringBuilderIntelMAT append(int value, int zeroPadWidth) {
            final boolean negative = value < 0;
            if (negative) {
                value = - value;
                if (value < 0) {
                    append("-2147483648");
                    return this;
                }
            }
            
            int index = reserve(11);
            final char[] chars = intel_mat_mChars;
            
            if (value == 0) {
                chars[index++] = '0';
                intel_mat_mLength += 1;
                return this;
            }
            
            if (negative) {
                chars[index++] = '-';
            }

            int divisor = 1000000000;
            int numberWidth = 10;
            while (value < divisor) {
                divisor /= 10;
                numberWidth -= 1;
                if (numberWidth < zeroPadWidth) {
                    chars[index++] = '0';
                }
            }
            
            do {
                int digit = value / divisor;
                value -= digit * divisor;
                divisor /= 10;
                chars[index++] = (char) (digit + '0');
            } while (divisor != 0);
            
            intel_mat_mLength = index;
            return this;
        }
        
        public FasterStringBuilderIntelMAT append(float value, int precision) {
            int scale = 1;
            for (int i = 0; i < precision; i++) {
                scale *= 10;
            }
            value = (float) (Math.rint(value * scale) / scale);
            
            append((int) value);

            if (precision != 0) {
                append(".");
                value = Math.abs(value);
                value -= Math.floor(value);
                append((int) (value * scale), precision);
            }
            
            return this;
        }
        
        @Override
        public String toString() {
            return new String(intel_mat_mChars, 0, intel_mat_mLength);
        }
        
        private int reserve(int length) {
            final int oldLength = intel_mat_mLength;
            final int newLength = intel_mat_mLength + length;
            final char[] oldChars = intel_mat_mChars;
            final int oldCapacity = oldChars.length;
            if (newLength > oldCapacity) {
                final int newCapacity = oldCapacity * 2;
                final char[] newChars = new char[newCapacity];
                System.arraycopy(oldChars, 0, newChars, 0, oldLength);
                intel_mat_mChars = newChars;
            }
            return oldLength;
        }
    }
}
